# number_video/views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
from django.db.models import Q
import json
import re
import logging
from cozepy import Coze, TokenAuth, Message, ChatEventType, COZE_CN_BASE_URL
from .models import GeneratedVideo

# 配置日志
logger = logging.getLogger(__name__)

# 初始化 Coze 客户端（不设置timeout）
coze_api_token = "pat_Ij5FuC1s4bV7MXYjZtCOZUiw6OTV0OPRxo57Bou3vC82PvMZee4RUrvy4l1O3YPv"
bot_id = 7540256305878270003
user_id = '123456789'

coze = Coze(
    auth=TokenAuth(token=coze_api_token),
    base_url=COZE_CN_BASE_URL
)


@csrf_exempt
def generate_video(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            prompt = data.get('prompt', '')

            if not prompt:
                return JsonResponse({'error': 'Missing prompt'}, status=400)

            # 输入验证
            if len(prompt.strip()) == 0:
                return JsonResponse({'error': 'Prompt cannot be empty'}, status=400)

            if len(prompt) > 1000:
                return JsonResponse({'error': 'Prompt too long'}, status=400)

            logger.info(f"Received prompt: {prompt}")

            # 使用标准方式构建消息
            messages = [
                Message.build_user_question_text(prompt)
            ]

            # 发起聊天请求并获取结果
            response_content = ""
            # 在stream方法中设置超时
            for event in coze.chat.stream(
                    bot_id=str(bot_id),
                    user_id=user_id,
                    additional_messages=messages,
                    timeout=3000  # 5分钟超时
            ):
                if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                    response_content += event.message.content

                if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                    logger.info("Chat completed successfully")

                    # 提取视频链接
                    video_url = extract_video_url(response_content)

                    if not video_url:
                        logger.error(f"No video URL found in response: {response_content}")
                        return JsonResponse({
                            'error': 'No video URL found in response'
                        }, status=500)

                    # 保存到数据库
                    try:
                        GeneratedVideo.objects.create(
                            title=f"{prompt[:30]}...",  # 使用提示词前30个字符作为标题
                            video_url=video_url,
                            prompt=prompt
                        )
                        logger.info(f"Video saved to database: {video_url}")
                    except Exception as e:
                        logger.error(f"Failed to save video to database: {e}")

                    return JsonResponse({
                        'status': 'success',
                        'video_url': video_url
                    })

        except json.JSONDecodeError as e:
            logger.error(f"JSON decode error: {e}")
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except Exception as e:
            logger.exception("Error in generate_video")
            error_msg = str(e)
            if 'timeout' in error_msg.lower():
                return JsonResponse({
                    'error': '视频生成超时，请稍后重试'
                }, status=500)
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Invalid request method'}, status=405)


def extract_video_url(content):
    """
    从内容中提取视频链接
    """
    # 匹配 http 或 https 开头的链接，通常视频链接以 .mp4 结尾
    video_pattern = r'https?://[^\s<>"]+?\.(?:mp4|avi|mov|wmv|flv|webm)'
    matches = re.findall(video_pattern, content)

    if matches:
        return matches[0]  # 返回第一个匹配的视频链接

    # 如果没有找到特定格式的视频链接，则尝试匹配任何 URL
    url_pattern = r'https?://[^\s<>"]+'
    urls = re.findall(url_pattern, content)

    if urls:
        return urls[0]  # 返回第一个匹配的链接

    return None


def get_video_list(request):
    """
    获取已生成的视频列表
    支持分页和搜索功能
    """
    if request.method == 'GET':
        try:
            # 获取分页参数
            page = int(request.GET.get('page', 1))
            size = int(request.GET.get('size', 10))

            # 获取搜索参数
            search = request.GET.get('search', '')

            # 构建查询
            queryset = GeneratedVideo.objects.all()

            # 如果有搜索参数，进行过滤
            if search:
                queryset = queryset.filter(
                    Q(title__icontains=search) |
                    Q(prompt__icontains=search)
                )

            # 分页处理
            paginator = Paginator(queryset, size)
            page_obj = paginator.get_page(page)

            # 构造返回数据
            videos = []
            for video in page_obj:
                videos.append({
                    'id': video.id,
                    'title': video.title,
                    'video_url': video.video_url,
                    'prompt': video.prompt,
                    'created_at': video.created_at.isoformat() if video.created_at else None
                })

            return JsonResponse({
                'videos': videos,
                'total': paginator.count,
                'page': page,
                'size': size,
                'pages': paginator.num_pages
            })
        except Exception as e:
            logger.exception("Error in get_video_list")
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Invalid request method'}, status=405)
